package com.campus.service.impl;

import com.alibaba.fastjson2.JSON;
import com.campus.common.Result;
import com.campus.entity.Categories;
import com.campus.entity.Posts;
import com.campus.entity.Users;
import com.campus.mapper.CategoriesMapper;
import com.campus.mapper.PostsMapper;
import com.campus.service.PostService;
import com.campus.utils.SnowFlakeUtil;
import com.campus.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseStatus;

@Service
public class PostServiceImpl implements PostService {
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private PostsMapper postsMapper;
    @Autowired
    private CategoriesMapper categoriesMapper;
    @Override
    public Result createPost(Posts post, String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 移除 "Bearer " 前缀
        }
        Users currentUser = tokenUtils.getCurrentUser(token);
        post.setPostId(SnowFlakeUtil.getId().toString());
        post.setUserId(currentUser.getUserId());
        post.setJsonImages(JSON.toJSONString(post.getImages()));
        String categoryId = categoriesMapper.selectCategoriesBySortOrder(post.getCategoryId());
        post.setCategoryId(categoryId);
        int i = postsMapper.insertPost(post);
        if(i>0){
            return Result.ok("帖子上传成功");
        }
        return Result.ok("帖子上传失败");
    }
}
